package com.notary.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.notary.entity.Contract;
import com.notary.entity.ContractCurrentStatus;
import com.notary.entity.ContractWorkFlow;
import com.notary.entity.Notary;
import com.notary.entity.po.ContractDTO;
import com.notary.entity.po.DepositDTO;
import com.notary.entity.po.ExecCertRequest;
import com.notary.entity.po.VideoOnlineDTO;
import com.notary.entity.vo.JsonResult;
import com.notary.mapper.ContractMapper;
import com.notary.seal.SealRequestService;
import com.notary.service.ContractCurrentStatusService;
import com.notary.service.ContractService;
import com.notary.service.ContractWorkFlowService;
import com.notary.service.NotaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 公证卷宗基本信息 前端控制器
 * </p>
 *
 * @author xujun
 * @since 2020-07-28
 */


@Api(tags = "公证卷宗基本信息控制器")
@RequestMapping("/contract")
@RestController
public class ContractController {


    @Resource
    ContractService contractService;

    @Autowired
    public ContractMapper contractMapper;

    @Autowired
    private ContractCurrentStatusService contractCurrentStatusService;

    @Autowired
    private NotaryService notaryService;

    @Autowired
    private SealRequestService sealRequestService;

    @Autowired
    public ContractController(ContractService contractService) {
        this.contractService = contractService;
    }

    /**
     * <p>
     * 根据条件查询全部记录（并翻页）
     * </p>
     */

    @ApiOperation(value = "列表查询")
    @GetMapping("/list")
    public JsonResult<IPage<JSONObject>> list(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, ContractDTO dto) {
        IPage<JSONObject> iPage = contractMapper.getContractPageList(new Page(pageNum, pageSize), dto);
        return JsonResult.success(iPage);
    }

    @ApiOperation(value = "列表金额统计查询")
    @GetMapping("/getTotal")
    public JsonResult getTotal(ContractDTO contractDTO) {
        return JsonResult.success(contractMapper.getchargeTotol(contractDTO));

    }

    /**
     * <p>
     * 查看案件详情
     * </P>
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping("/getContractViewById/{id}")
    public JsonResult getContractViewById(@PathVariable("id") Long id, HttpServletRequest httpServletRequest) {
        return contractService.getContractViewById(id, httpServletRequest);
    }

    /**
     * <p>
     * H5通过卷宗号查询公证书
     * </P>
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping("/getByNotaryNo/{notaryNo}")
    public JsonResult getByNotaryNo(@PathVariable("notaryNo") String notaryNo) {
        return contractService.getByNotaryNo(notaryNo);
    }

    /**
     * <p>
     * 保存对象-如果对象存在则修改原数据，否则插入一条新数据
     * </p>
     */
    @ApiOperation(value = "保存对象")
    @GetMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(@RequestBody Contract contract) {
        return JsonResult.success(contractService.saveOrUpdate(contract));
    }


    /**
     * <p>
     * 根据 id删除记录-逻辑删除
     * </p>
     */
    @ApiOperation(value = "删除")
    @GetMapping("/remove/{id}")
    public JsonResult removeById(@PathVariable("id") Integer id) {
        return JsonResult.success(contractService.removeById(id));

    }

    /**
     * <p>
     * 案件新增
     * </p>
     */
    @ApiOperation(value = "save")
    @PostMapping("/save")
    public JsonResult save(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) throws Exception {
        return contractService.addContract(dto, httpServletRequest);

    }
    /**
     *<p>
     * 查看待我处理案件列表
     *</p>
     */
  /*  @ApiOperation(value = "findMyDo")
    @GetMapping("/findMyDo")
    public JSONResult findMyDo(HttpServletRequest request,ContractDTO dto) {
        return contractService.findMyDo(request,dto);
    }
*/

    /**
     * <p>
     * 查看待我处理案件列表
     * </p>
     */
    //check0
    @ApiOperation(value = "初核")
    @PostMapping("/chuhe")
    public JsonResult chuhe(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) {
        return contractService.chuhe(dto, httpServletRequest);
    }

    /**
     * <p>
     * 查看待我处理案件列表
     * -1不予受理   1申请与初核  2受理  3审查  4审批 -2拟定公证词 5制证 6发证 7归档 8收费
     * </p>
     */
    @ApiOperation(value = "受理")
    @PostMapping("/shouli")
    public JsonResult shouli(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) {
        return contractService.shouli(dto, httpServletRequest);
    }

    @ApiOperation(value = "审查")
    @PostMapping("/shencha")
    public JsonResult shencha(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) {
        return contractService.shencha(dto, httpServletRequest);
    }

    @ApiOperation(value = "审批")
    @PostMapping("/shenpi")
    public JsonResult shenpi(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) {
        return contractService.shenpi(dto, httpServletRequest);
    }

    @ApiOperation(value = "拟定公证词")
    @PostMapping("/nici")
    public JsonResult nici(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) throws Exception {
        return contractService.nici(dto, httpServletRequest);
    }

    @ApiOperation(value = "制证")
    @PostMapping("/zhizheng")
    public JsonResult zhizheng(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) throws Exception {
        return contractService.zhizheng(dto, httpServletRequest);
    }

    @ApiOperation(value = "发证")
    @PostMapping("/fazheng")
    public JsonResult fazheng(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) {
        return contractService.fazheng(dto, httpServletRequest);
    }

    @ApiOperation(value = "执行证书")
    @PostMapping("/zhixing")
    public JsonResult zhixing(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) throws Exception {
        return contractService.zhixing(dto, httpServletRequest);
    }

    @ApiOperation(value = "核实函书")
    @PostMapping("/heshihan")
    public JsonResult heshihan(@RequestBody ContractDTO dto, HttpServletRequest httpServletRequest) throws Exception {
        return contractService.heshihan(dto, httpServletRequest);
    }

    /**
     * <p>
     * 预览 富文本
     * </p>
     */
    @ApiOperation(value = "预览 富文本")
    @PostMapping("/preview")
    public JsonResult preview(@RequestBody ContractDTO dto, HttpServletRequest request) {
        return contractService.preview(dto, request);
    }

    /**
     * <p>
     * 上传附件
     * </p>
     */
    @ApiOperation(value = "上传附件")
    @PostMapping("/addFile")
    public JsonResult addFile(@RequestBody ContractDTO dto) {
        return contractService.addFile(dto);
    }

/*
    @ApiOperation(value = "获取推送过来待初核数据")
    @PostMapping("/getSendDataList")
    public JSONResult<IPage<JSONObject>> getSendDataList(@RequestBody ContractDTO dto) {
        dto.setStatus(1);
        IPage<JSONObject> iPage= contractMapper.getSendDataList(new Page(dto.getPageNum(),dto.getPageSize()),dto);
        return JSONResult.success(iPage);
    }
*/

    @ApiOperation(value = "findMyDo")
    @PostMapping("/findMyDo")
    public JsonResult<IPage<JSONObject>> findMyDo(HttpServletRequest request, @RequestBody ContractDTO dto) {
        String owner = contractService.getNotaryId(request).toString();
        dto.setOwner(owner);
        IPage<JSONObject> iPage = contractMapper.findMyDo(new Page(dto.getPageNum(), dto.getPageSize()), dto);
        return JsonResult.success(iPage);
    }

    /**
     * 申请执行证书
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "申请执行证书")
    @PostMapping("/applyExecCert")
    public JsonResult applyExecCert(@RequestBody ExecCertRequest request) {
        return contractService.applyExecCert(request);
    }

    @ApiOperation(value = "申请执行证书列表")
    @GetMapping("/applyExecCert/list")
    public JsonResult applyExecCertList(int pageNum, int pageSize, ContractDTO dto) {
        //dto.setExecutionType(100);
        IPage<JSONObject> iPage = contractMapper.getContractPageList(new Page(pageNum, pageSize), dto);

        return JsonResult.success(iPage);
    }

    /**
     * 检查是否拥有签名
     */
    @ApiOperation(value = "检查是否拥有签名")
    @GetMapping("/checkCustNo")
    public JsonResult checkCustNo(HttpServletRequest request) {
        return contractService.checkCustNo(request);
    }


    /**
     * 检查是否拥有签名
     */
    @ApiOperation(value = "公证员连线")
    @PostMapping("/online")
    public JsonResult online(@RequestBody VideoOnlineDTO videoOnlineDTO) {
        return contractService.online(videoOnlineDTO);
    }

    /**
     * <p>
     * 根据卷宗id查看当前卷宗操作人
     * </P>
     */
    @ApiOperation(value = "根据id查询当前卷宗操作人")
    @GetMapping("/getContractOwner/{id}")
    public JsonResult getContractOwner(@PathVariable("id") Long id) {
        if (Objects.isNull(id)) {
            return JsonResult.fail("卷宗id不能为空！");
        }
        QueryWrapper<ContractCurrentStatus> currentStatusQueryWrapper = new QueryWrapper<>();
        currentStatusQueryWrapper.eq("contract_id", id);
        currentStatusQueryWrapper.orderByDesc("create_time");
        ContractCurrentStatus contractCurrentStatus = contractCurrentStatusService.list(currentStatusQueryWrapper).get(0);
        Notary notary = notaryService.getById(contractCurrentStatus.getOwner());
        if (notary != null) {
            return JsonResult.success(notary);
        }
        return JsonResult.fail("获取操作人失败！");
    }

    /**
     * 存证下载
     * @param hashCode
     */
    @ApiOperation(value = "存证下载")
    @GetMapping("/downloadDeposit")
    public void downloadDeposit(String hashCode, String password, HttpServletResponse response) {
        contractService.downloadDeposit(hashCode,password,response);
    }

    /**
     * 存证校验
     * @param file
     * @param hashCode
     */
    @ApiOperation(value = "存证校验")
    @PostMapping("/verifyDeposit")
    public JsonResult verifyDeposit(@RequestParam(value = "file",required = false) MultipartFile file , @RequestParam(value = "hashCode",required = false) String hashCode , @RequestParam(value = "originalHash") String originalHash) {
        if (Objects.isNull(originalHash)) {
            return JsonResult.fail("源文件哈希值不能为空！");
        }
        if (Objects.isNull(hashCode) && Objects.isNull(file)) {
            return JsonResult.fail("存证校验哈希值或者源文件不能为空！");
        }
        return contractService.verifyDeposit(file,hashCode,originalHash);
    }

    /**
     * 获取存证管理列表数据
     * @param dto
     */
    @ApiOperation(value = "获取存证管理列表数据")
    @PostMapping("/getDepositList")
    public JsonResult getDepositList(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, DepositDTO dto) {
        return contractService.getDepositList(pageNum,pageSize,dto);
    }

    @ApiOperation(value= "更新")
    @PostMapping("/updateCertificateFile")
    public JsonResult updateCertificateFile(
            @RequestParam("notaryNo") String notaryNo,
            @RequestParam("type") String type,
            @RequestParam("file") String file) {
        return sealRequestService.updateCertificateFile(notaryNo, type, file);
    }
}
